from django.shortcuts import render
from django.views import View
# Create your views here.
from django.http import JsonResponse,HttpResponse
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.answer.models import Label, Question, Reply
from apps.answer.serializer import LabelSerializer, AnswerSerializer, IssueSerializer, IssueDatailsSerializer, \
    ReplySerializer, LablesSerializer


class AllLabels(APIView):
    # 所有标签列表
    def get(self,request):
        queryset=Label.objects.all()
        serializer=LabelSerializer(queryset,many=True)
        return Response(serializer.data)


class UserLabels(APIView):
    '''用户关注的标签'''
    def get(self,request):
        queryset=Label.objects.filter(label_name=Label.users)
        serializer=LabelSerializer(queryset,many=True)
        return Response(serializer.data)


class NewAnswers(APIView):
    '''最新回答的问题'''
    def get(self,request,id):
        if id== -1:
            queryset=Question.objects.all().order_by("-createtime")
        else:
            queryset=Question.objects.filter(id=id).order_by("-createtime")
        serializer=AnswerSerializer(queryset,many=True)
        return Response(serializer.data)


class HotAnswers(APIView):
    '''热门回答问题'''
    def get(self,request,id):
        if id == -1:
            queryset=Question.objects.all().order_by("-reply","-visits")
        else:
            queryset=Question.objects.filter(id=id).order_by("-reply","-visits")
        serializer=AnswerSerializer(queryset,many=True)
        return Response(serializer.data)


class IssueAnswers(ModelViewSet):
    '''发布问题'''
    # permission_classes = [IsAdminUser]
    # def ger(self,request):
    #     user=request.user
    #     serializer=IssueSerializer(data=request.data)
    #     set=serializer.is_valid(raise_exception=True)
    #     set.save()
    #     return Response({"message":"发布成功","success":True})
    def create(self, request, *args, **kwargs):
        user=request.user
        data=request.data
        data["user"]=user.id
        serializer=IssueSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"message":"ok","success":True})



class IssueDatails(APIView):
    '''问题详情'''
    def get(self,request,id):
        data=Question.objects.filter(id=id)
        serializer=IssueDatailsSerializer(data,many=True)
        return Response(serializer.data)


class YesUsefulView(APIView):
    '''回答有用'''
    permission_classes = [IsAdminUser]
    def put(self,request,id):
        user=request.id
        conn=get_redis_connection('permission')
        res=conn.hget("per_%s" %user,user.id)
        if res :
            return Response({"message":'操作频繁',"success":False})
        try:
            queryset=Question.objects.filter(id=id)
            queryset.useful_count+=1
            queryset.save()
            conn.hset("per_%s" % user, user.id, 3)

        except Exception as e:
            return Response({"message":"数据库错误","success":False})
        return Response({"message":"ok","success":True})


class NoUsefulView(APIView):
    '''问题无用'''
    permission_classes = [IsAdminUser]
    def put(self,request,id):
        user=request.id
        conn=get_redis_connection("nopermission")
        res=conn.hget("nopeim_%s" %user,user.id)
        if res :
            return Response({"message":"请勿频繁操作","success":False})
        try:
            queryset=Question.objects.filter(id=id)
            queryset.unuseful_count+=1
            queryset.save()
            conn.hset("nopeim_%s" %user,user.id,3)
        except Exception as e:
            return Response({"message":"数据库错误","success":False})
        return Response({"message":"ok","success":True})


class ReplyView(APIView):
    '''回答问题'''
    permission_classes = [IsAdminUser]
    def post(self,request):
        serializer=ReplySerializer(data=request.data)
        res=serializer.is_valid()
        if res:
            res.save()
            return Response({"message":"ok","success":True})
        return Response({"message":"no","success":False})


class YesReplyView(APIView):
    '''回答有用'''
    def put(self,request,id):
        user=request.id
        conn=get_redis_connection("yesReplView")
        res=conn.hget("reply_%s"%user,user.id)
        if res:
            return Response({"message":"请勿频繁操作","success":False})
        try:
            queryset=Reply.objects.filter(id=id)
            queryset.useful_count+=1
            queryset.save()
            conn.hset('reply_%s'%user,user.id,3)
        except Exception as e:
            return Response({"message":"ok","success":False})
        return Response({"message": "ok", "success": True})


class NoReplyView(APIView):
    '''回答无用'''
    permission_classes = [IsAdminUser]
    def put(self,request,id):
        user=request.id
        conn=get_redis_connection("nopreply")
        res=conn.hget("reply_%s"%user,user.id)
        if res :
            return Response({"message":"no","success":False})
        try:
            queryser=Reply.objects.filter(id=id)
            queryser.unuseful_count+=1
            queryser.save()
        except Exception as e:
            return Response({"message":"no","success":False})
        return Response({'message':"ok","success":True})


class Focusin(APIView):
    '''关注标签'''
    permission_classes = [IsAdminUser]
    def put(self,request,id):
        user=request.user
        label=Label.objects.filter(id=id)
        if not user in label.users:
            label=label.users.add['user']
            # label.save()
            return Response({"message":"关注成功","success":True})
        return Response({"message":"已经关注了","success":False})

class NoFocusin(APIView):
    '''取消标签'''
    permission_classes = [IsAdminUser]
    def put(self,request,id):
        user=request.user
        label=Label.objects.filter(id=id)
        if user in label.users:
            label=label.users.pop["user"]
            label.save()
            return Response({"message":"取消关注","success":True})
        # return Response({"message":"已经关注了","success":False})


class LabelsView(GenericAPIView):
    '''标签详情'''
    serializer_class = LabelSerializer
    def get(self,request,id):
        data=Label.objects.filter(id=id)
        serializer=LablesSerializer(data)
        return Response(serializer.data)